<template>
    <van-nav-bar title="邮箱认证" left-text="" left-arrow @click-left="goBack" />
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <!-- 邮箱 -->
            <van-field v-model="LoginUser.email" name="email" label="邮箱" placeholder="请输入邮箱" readonly />
            <!-- 邮箱验证码 -->
            <van-field v-model="code" center clearable label="邮箱验证码" placeholder="请输入邮箱验证码"
                :rules="[{ required: true, message: '请填写邮箱验证码' }]">
                <template #button>
                    <van-button size="small" type="primary" @click="send" :disabled ="status">
                        <span v-if="!status">发送验证码</span>
                        <!-- 倒计时 -->
                        <van-count-down v-show="status" ref="countDown" millisecond :time="10000" :auto-start="false" :format="format" @finish="onFinish" />
                    </van-button>
                </template>
            </van-field>
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>

</template>

<script setup>
const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.push('/business/index') }
const LoginUser = reactive(proxy.$cookies.get('LoginUser') ?? {})
const code = ref('')
const countDown = ref(null);
const format = 'ss秒'
const status = ref(false)

const send = async() => {
    status.value = true
    // 开始倒计时
    countDown.value.start();
    let result = await Api.send({
        busid: LoginUser.id
    })
    if(result.code == 1)
    {
        success(result.msg);
    }
    else
    {
        error(result.msg);
    }
}

const onFinish = () =>{
    status.value = false;
    // 重置方法
    countDown.value.reset();
}

const onSubmit = async() =>{
    let result = await Api.email({
        busid: LoginUser.id,
        code: code.value
    })
    if (result.code == 1) 
    {
        success({
            message: result.msg,
            onClose: () => {
                proxy.$router.push('/business/index')
            }
        });
    }
    else 
    {
        error(result.msg);
    }
}
</script>
